<style lang="less" scoped>
  .pay_course {
    width: 100%;
    height: 100%;
    > header{
      width: 100%;
      height: 88px;
      line-height: 88px;
      text-align: center;
      font-size: 32px;
      color: #333333;
      background: #fff;
      border-bottom: 1px solid #F5F5F5;
      position: relative;
      // position: fixed;
      // top: 0;
      // left: 0;
      // z-index: 20;
      .icon-box{
        width: 80px;
        height: 88px;
        position: absolute;
        left: 0px;
        top:0px;
        display: flex;
        justify-content: center;
        align-items: center;
      }
    }
    .nav {
      width: 100%;
      height: 116px;
      padding: 18px 30px;
      // position: fixed;
      // top: 88px;
      // left: 0;
      // z-index: 20;
      display: flex;
      justify-content: space-between;
      align-items: center;
      border-bottom: 1px solid #F5F5F5;
      background: #fff;
      > .tabs {
        width: 100%;
        height: 100%;
        display: flex;
        justify-content: flex-start;
        align-items: center;
        overflow-x: scroll;
        position: relative;
        > .tab {
          height: 54px;
          margin-right: 25px;
          font-size: 28px;
          color: #ACACAC;
          padding: 7px 22px;
          background: #F5F5F5;
          border-radius: 27px;
          display: flex;
          justify-content: center;
          align-items: center;
          border: 1px solid transparent;
          &:last-child {
            margin-right: 0px;
          }
          &.checked {
            background: rgba(91,118,255,0.1);
            border-radius: 27px;
            border: 1px solid #5B76FF;
            color: #5B76FF;
          }
          > i {
            width: 22px;
            height: 22px;
            margin-right: 4px;
            background: url('../assets/images/zxjtqh/pv_fire_type1.png') center/100% no-repeat;
          }
          > .icons {
            width: 12px;
            height: 24px;
            margin-left: 10px;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            > .top {
              width: 12px;
              height: 12px;
              background: url('../assets/images/price_up.png') center/100% no-repeat;
              &.light {
                background: url('../assets/images/price_down.png') center/100% no-repeat;
                transform: rotateZ(180deg);
              }
            }
            > .bottom {
              width: 12px;
              height: 12px;
              background: url('../assets/images/price_up.png') center/100% no-repeat;
              transform: rotateZ(180deg);
              &.light {
                background: url('../assets/images/price_down.png') center/100% no-repeat;
                transform: rotateZ(0deg);
              }
            }
          }
        }
      }
    }
    .content {
      width: 100%;
      height: calc(100% - 116px - 88px);
      border-bottom: constant(safe-area-inset-bottom) solid transparent;
      border-bottom: env(safe-area-inset-bottom) solid transparent;
      // padding-bottom: constant(safe-area-inset-bottom); /*兼容 IOS<11.2*/
      // padding-bottom: env(safe-area-inset-bottom); /*兼容 IOS>11.2*/
      overflow: hidden;
      // position: fixed;
      // top: calc(88px + 116px);
      // left: 0;
      // z-index: 20;
      .loading {
        width: 100%;
        height: 500px;
        display: flex;
        > i {
          width: 80px;
          height: 80px;
          margin: auto;
          background: url('../assets/images/refresh.png') center/100% no-repeat;
          animation: load .5s ease-in-out 0s infinite;
          @keyframes load {
            0% {
              transform: rotateZ(0deg);
            }
            100% {
              transform: rotateZ(360deg);
            }
          }
        }
      }
      .empty {
        width: 100%;
        height: 500px;
        display: flex;
        > span {
          height: 100px;
          margin: auto;
          white-space: nowrap;
          font-size: 26px;
          color: #999;
        }
      }
      .inner {
        min-height: 100%;
        > li {
          padding: 30px 20px;
          border-bottom: 1px solid #F5F5F5;
          font-size: 0;
          .avatar {
            width: 190px;
            height: 190px;
            margin-right: 20px;
            display: inline-block;
            border-radius: 12px;
            position: relative;
            overflow: hidden;
            > img {
              width: 100%;
              height: 100%;
              font-size: 0;
            }
            .lesson_info {
              width: 100%;
              height: 40px;
              line-height: 40px;
              position: absolute;
              left: 0;
              bottom: 0;
              background: linear-gradient(180deg, rgba(0,0,0,0) 0%, rgba(0,0,0,0.4) 100%);
              text-align: right;
              font-size: 20px;
              color: #fff;
              padding-right: 4px;
            }
          }
          .info {
            width: calc(100% - 190px - 20px);
            height: 190px;
            display: inline-block;
            position: relative;
            .title_area {
              width: 100%;
              height: 88px;
              position: absolute;
              top: 0;
              left: 0;
              display: flex;
              flex-direction: column;
              justify-content: space-between;
              align-items: flex-start;
              .title {
                width: 100%;
                height: 42px;
                display: flex;
                justify-content: flex-start;
                align-items: center;
                > i {
                  height: 32px;
                  line-height: 32px;
                  padding: 0px 4px;
                  font-style: normal;
                  background: #5B76FF;
                  color: #FFF;
                  font-size: 20px;
                  white-space: nowrap;
                  border-radius: 5px;
                  margin-right: 10px;
                }
                > span {
                  color: #333;
                  font-size: 30px;
                  white-space: nowrap;
                  flex: 1;
                  overflow: hidden;
                  text-overflow: ellipsis;
                  white-space: nowrap;
                }
              }
              .sub_title {
                width: 100%;
                height: 37px;
                line-height: 37px;
                font-size: 26px;
                color: 999;
                overflow: hidden;
                text-overflow: ellipsis;
                white-space: nowrap;
              }
            }
            .price_area {
              width: 100%;
              height: 60px;
              position: absolute;
              left: 0;
              bottom: 0;
              display: flex;
              justify-content: space-between;
              align-items: center;
              .price {
                height: 100%;
                display: flex;
                justify-content: flex-start;
                align-items: center;
                letter-spacing: -1px;
                .span1 {
                  font-size: 32px;
                  color: #FF0000;
                }
                .span2 {
                  color: #999999;
                  font-size: 20px;
                  margin-left: 5px;
                  text-decoration: line-through;
                }
              }
              .btn {
                height: 100%;
                display: flex;
                justify-content: flex-end;
                align-items: center;
                .pv {
                  display: flex;
                  justify-content: flex-start;
                  align-items: center;
                  margin-right: 10px;
                  > i {
                    width: 24px;
                    height: 24px;
                    margin-right: 4px;
                    background: url('../assets/images/zxjtqh/pv_fire_type2.png') center/100% no-repeat;
                    transform: translateY(-2px);
                  }
                  > span {
                    color: #FF7A00;
                    font-size: 22px;
                  }
                }
                .buy {
                  height: 60px;
                  padding: 9px 24px;
                  border: 1px solid #5B76FF;
                  color: #5B76FF;
                  font-size: 30px;
                  display: flex;
                  border-radius: 30px;
                  span {
                    margin: auto;
                  }
                  &.haveBuy {
                    border: 1px solid #ECECEC;
                    color: #999;
                    background: #ECECEC;
                  }
                }
              }
            }
          }
        }
        .pullup-tips {
          padding: 20px;
          text-align: center;
          color: #999;
        }
      }
    }
  }
</style>

<template>
  <!-- 全部精品课程页面 -->
  <div class="pay_course">
    <!-- 头部 -->
    <header>
      <div class="icon-box" @click="back()">
        <van-icon name="arrow-left" size="1.2rem" color="#333333"/>
      </div> 				
      <p>精品课程</p>
    </header>
    <div class="nav">
      <div class="tabs" ref="tabs">
        <div class="tab" :class="{checked: curClass === index}" v-for="(item, index) in tabsList" :key="index" @click="() => onSwitchTab(index)">
          <i v-if="item.openIcon"></i>
          <span>{{item.text}}</span>
          <div class="icons" v-if="item.openSort">
            <i class="top" :class="{light: sortType == 1}"></i>
            <i class="bottom" :class="{light: sortType == 2}"></i>
          </div>
        </div>
      </div>
    </div>
    <div class="content" ref="content">
      <div class="loading" v-if="loading"><i></i></div>
      <div class="empty" v-else-if="!courseList.length"><span>暂时没有数据</span></div>
      <ul class="inner" ref="inner" v-else>
        <li v-for="(item, index) in courseList" :key="index" @click=" handleEnterCourse(item)">
          <div class="avatar">
            <img :src="item.imgUrl+ '?x-oss-process=image/resize,m_fixed,h_190,w_190'" alt="">
            <div class="lesson_info">{{item | lessonFilter}}</div>
          </div>
          <div class="info">
            <div class="title_area">
              <div class="title"><i v-if="item.totalLessonNum && item.totalLessonNum > 1">系列</i><span>{{item.title}}</span></div>
              <div class="sub_title">{{item.subTitle}}</div>
            </div>
            <div class="price_area">
              <div class="price"><span class="span1">{{item | priceFilter}}</span><span class="span2" v-if="(item.priceType === 1 && item.buyPrice && item.linePrice)">￥{{item.linePrice}}.00</span></div>
              <div class="btn">
                <div class="pv"><i></i><span>{{item.pv}}</span></div>
                <div class="buy" :class="{haveBuy: item.hasBuy}"><span>{{item | btnFileter}}</span></div>
              </div>
            </div>
          </div>
        </li>
        <div class="pullup-tips" v-if="showPullup">
          <div v-if="!isPullUpLoad" class="before-trigger">
            <span class="pullup-txt">{{isNoMore ? '没有更多数据了' : '上拉加载更多'}}</span>
          </div>
          <div v-else class="after-trigger">
            <span class="pullup-txt">加载中...</span>
          </div>
        </div>
      </ul>
    </div>
  </div>
</template>

<script>
  import BScroll from '@better-scroll/core';
  import Pullup from '@better-scroll/pull-up';
  import store from "../store/index";
  import {dotNum} from '@/util/api.js'
  BScroll.use(Pullup);

  export default {
    name: "niceCourse",
    data() {
      return {
        tabsList: [],
        curClass:0,
        curTabIndex: 1,
        preTabIndex: 0,
        sortType: 0, // 0 降序 1 升序 
        courseList: [],
        sortOrder:'desc',
        page: 1,
        pageSize: 10,
        loading: false,
        isReq: false,
        showPullup: false,
        isPullUpLoad: false,
        isNoMore: false,
      }
    },
    filters: {
      lessonFilter(item) {
        const { hasFinishLessonNum, totalLessonNum } = item;
        if (totalLessonNum) {
          if (hasFinishLessonNum === totalLessonNum) {
            return `共${totalLessonNum}节`
          } else {
            return `更新至${hasFinishLessonNum > 9 ? hasFinishLessonNum : '0' + hasFinishLessonNum}节`;
          }
        } else {
          return `更新至${hasFinishLessonNum > 9 ? hasFinishLessonNum : '0' + hasFinishLessonNum}节`;
        }
      },
      priceFilter(item) {
        const { priceType, buyPrice, validType } = item;
        if (priceType === 0) {
          // 免费
          if (validType === 0) {
            // 永久有效
            return '免费';
          } else {
            // 其他有效期
            return '限时免费';
          }
        } else {
          // 付费
          if (buyPrice) {
            // 有价格
            return `￥${buyPrice}.00`;
          } else {
            // 没价格
            return '付费';
          }
        }
      },
      btnFileter(item) {
        const { priceType, hasBuy } = item;
        if (priceType === 0) {
          // 免费
          if (hasBuy) {
            return '已订阅';
          } else {
            return '订阅';
          }
        } else {
          // 付费
          if (hasBuy) {
            return '已购买';
          } else {
            return '购买';
          }
        }
      }
    },
    computed: {
      // index和type切换
      indexAndTypeChange() {
        return [this.sortOrder, this.curTabIndex,this.sortType];
      }
    },
    watch: {
      // 切换index和type刷新数据
      indexAndTypeChange: {
        handler() {
          this.bs.scrollTo(0, 0, 0);
          this.bs?.destroy();
          this.courseList = [];
          this.showPullup = false;
          this.isPullUpLoad = false;
          this.isNoMore = false;
          // 请求新数据
          this.getCourseList();
        },
      }
    },
    beforeRouteEnter(to, from, next) {
      // 跳转精品课程列表手机验证检查（区分platform: wx web app）
      console.log('机构：', window.channel);
      if (to.fullPath.indexOf('/zxjtqh/niceCourse') !== -1||to.fullPath.indexOf('/neworg1/niceCourse') !== -1) {/* neworg1 zxjtqh */
        if (store.state.userInfo.hasBindMobile === true) {
          next();
        } else {
          if(window.terminal.isZxjtqhApp){
            if(store.state.isYk){
              console.log('进入课程更多，platform: app','游客');
              fun.gotoLogin()
            }else{
              next();
            }      
          }else if(window.terminal.weixin){
              console.log('进入课程更多，platform: wx');
              const sessionData = window.sessionStorage.getItem(`${window.channel}CourseSms`)
              sessionData ? next() :store.commit('setGlobalPopupInfo', {
                ...store.state.globalPopupInfo,
                type: 0,
                show: true,
                next,
                from,
              })
          }else{
            console.log('进入课程更多，platform: web');
            const sessionData = window.sessionStorage.getItem(`${window.channel}CourseSms`)
            sessionData ? next() :store.commit('setGlobalPopupInfo', {
                ...store.state.globalPopupInfo,
                type: 0,
                show: true,
                next,
                from,
              })
          }
        }
			} else {
        Vue.prototype.$myrouter.push(`/${window.channel}/home`);
        fun.toastMessage('机构匹配异常');
      }
    },
    created() {
      dotNum('moreCoursePage')
    },
    mounted() {
      // 获取tabList
      this.getTabList();
      // 获取courseList
      this.getCourseList();
    },
    methods: {
      back(){
        this.$router.replace(`/${this.$channel}/home`);
      },
      // 获取tablist数据
      getTabList() {
        this.tabsList = [
          {
            text: '最新',
            openIcon: false,
            openSort: false,
          }, 
          {
            text: '热门',
            openIcon: true,
            openSort: false,
          }, 
          {
            text: '价格',
            openIcon: false,
            openSort: true,
          }, 
        ];
        // 计算tablist
        this.$nextTick(() => {
          const wrapNode = this.$refs.tabs;
          this.wrapWidth = wrapNode.clientWidth;
          this.itemWidthList = Array.from(wrapNode.childNodes, item => {
            return {
              width: item.clientWidth, 
              leftDis: item.offsetLeft,
            }
          })
        })
      },
      // tab切换
      onSwitchTab(index) {
        if (this.isReq) {
          fun.toastMessage('数据获取中...');
          return false;
        };
        this.page = 1; // 设置page = 1
        if(index == 1){
          this.curTabIndex = 0
          this.sortOrder = 'desc'
          this.sortType = 0
        }else if(index == 2){
            if(this.sortType == 0 || this.sortType == 2){
              this.sortOrder = 'asc'//倒叙
              this.sortType = 1
            } else{
              this.sortOrder = 'desc'//倒叙
              this.sortType = 2
            }                
          this.curTabIndex = 2          
        }else{
          this.sortType = 0
          this.curTabIndex = 1
          this.sortOrder = 'desc'
        }
        this.curClass = index;
        const { width, leftDis } = this.itemWidthList[index];
        this.$refs.tabs.scrollTo({
          top: 0,
          left: leftDis - this.wrapWidth / 2 + width / 2,
          behavior: 'smooth',
        });
      },
      // 获取courseList数据
      async getCourseList() {
        this.loading = true;
        await this.requestData();
        this.loading = false;
        this.$nextTick(() => {
          this.bs =  new BScroll('.content', {
            pullUpLoad: true,
            click: true,
          })
          // 判断是否需要上拉加载
          if(this.courseList.length !== 0 && this.$refs.inner.clientHeight > this.$refs.content.clientHeight) {
            this.showPullup = true;
            this.$nextTick(() => {
              this.bs.refresh();
              this.bs.on('pullingUp', this.pullingUpHandler);
            })
          }
        })
      },
      async pullingUpHandler() {
        this.isPullUpLoad = true;
        this.page += 1;
        await this.requestData();
        this.bs.finishPullUp();
        this.bs.refresh();
        this.isPullUpLoad = false;
        if (this.isNoMore) this.bs.closePullUp();
      },
      requestData() {
        return new Promise(resolve => {
          this.isReq = true;
          this.$http.get("/h5live/course/getNiceCourses", {
            params: {
              sort: this.curTabIndex,
              sortOrder: this.sortOrder,
              page: this.page,
              pageSize: this.pageSize,
              homeShow:0,
            },
          }).then(res => {
            this.isReq = false;
            if(res.data.code === "000000") {
              if (res.data.data.length === 0) this.isNoMore = true;
              this.courseList = [...this.courseList, ...res.data.data];
              resolve();
            } else {
              return Promise.reject(res.data);
            }
          }).catch(err => {
            console.error(err);
          });
        })
      },
      // 判断课程详情/课节
      handleEnterCourse(item) {
        const {courseId} = item 
        this.$router.push(`/${this.$channel}/courseDetail?courseId=${courseId}`)
      },
    }
  };
</script>
